<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {

        $users = User::all();
        $roles = Role::pluck("role_name", "id");
        return view("admin.user.index", [
            "users" => $users,
            "pageName" => "用户列表",
            "roles" => $roles
        ]);
    }

    public function create()
    {
        $roles = Role::pluck("role_name", "id");
        return view("admin.user.create", [
            "pageName" => "添加用户",
            "roles" => $roles
        ]);
    }

    public function save(Request $request)
    {
        $user = new User();
        $user->user_name = $request->post("user_name");
        $user->user_phone = $request->post("user_phone");
        $user->user_password = password_hash($request->post("user_password"), PASSWORD_DEFAULT);
        $user->role_id = $request->post("role_id");
        $user->save();

        return redirect()->route("adminUserIndex");

    }

    public function delete(Request $request)
    {
        $id = $request->input("id");
        User::destroy($id);

        return redirect()->route("adminUserIndex");

    }

    public function edit(Request $request)
    {
        $id = $request->input("id");
        $roles = Role::pluck("role_name", "id");
        $user = User::find($id);

        return view("admin.user.edit", [
            "user" => $user,
            "roles" => $roles,
            "pageName" => "编辑用户",
        ]);
    }
    public function update(Request $request)
    {
        $id = $request->input("id");
        $user = User::find($id);
        $user->user_name = $request->post("user_name");
        $user->user_phone = $request->post("user_phone");
        $user->role_id = $request->post("role_id");
        $user->save();
        return redirect()->route("adminUserIndex");

    }
}
